<template>
  <div>
    <el-upload
      class="upload-demo"
      :on-success="fileSuccess"
      :file-list="attachList"
      :multiple="false"
      :before-upload="beforeUpload"
      action="#"
      :show-file-list="false"
      :http-request="toUpload"
    >
      <span>
        <slot name="default"></slot>
      </span>
    </el-upload>
  </div>
</template>
<script lang="ts">
import {
  defineComponent,
  computed,
  onBeforeMount,
  reactive,
  toRefs,
  ref,
  onMounted,
  watchEffect,
} from "vue";
import { downloadFile } from "@/utils/download";
import { uploadOss } from "@/api/user";
import { ElMessage } from "element-plus";

export default defineComponent({
  name: "ossUpload",
  props: {
    modelValue: {
      type: Array,
      default: () => {
        return [];
      }, // quarter=季度; halfYear=半年
    },
    title: {
      type: String,
      default: () => "",
    },
    limit: {
      type: String,
      default: () => "defaultLimit",
    },
  },
  setup(props, { emit }) {
    const state = reactive({
      attachList: [],
    });

    const toUpload = async (param: any) => {
      return new Promise(async (resolve, reject) => {
        let file = param.file;
        emit("start",file);
        let formData = new FormData();
        formData.append("file", file);
        formData.append("fileName", file.name);
        let res;
        res = await uploadOss(formData);
        if (res.status == 0) {
          resolve(res);
        } else {
          ElMessage.error(res.message);
          reject(res);
        }
      });
    };

    const fileSuccess = (res, file) => {
      //debugger;
      state.attachList.push({
        name: file.name,
        url: res.data,
        sort: 1,
        uid: file.uid,
      });
      emit("complete", getOssfileUrl(res.data));
    };

    const getfilePath = (url, name = "filePath") => {
      if (!url) {
        return "";
      }
      var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
      var r = url.split("?")[1].match(reg);
      if (r != null) return unescape(r[2]);
      return null;
    };

    function getOssfileUrl(filePath: string) {
      // 获取auth 、usercode
      return `http://localhost:8008/hramis/file/download?filePath=${filePath}`;
    }

    const beforeUpload = (file: any) => {
      const isSize = file.size / 1024 / 1024 < 10;
      const fileName = file.name;
      const fileType = fileName.substring(fileName.lastIndexOf("."));
      console.log("limit", props.limit);
      let isType;
      if (props.limit == "defaultLimit") {
        isType = [".jpg", ".jpeg", ".png", ".doc", ".docx", ".pdf",'.mp4'].includes(
          fileType.toLowerCase()
        );
      } else if (props.limit == "pdf") {
        isType = [".pdf"].includes(fileType.toLowerCase());
      }

      if (!isType) {
        if (props.limit == "defaultLimit") {
          ElMessage.warning(`仅支持【doc, docx, pdf, jpg, jpeg, png】文件!`);
        } else if (props.limit == "pdf") {
          ElMessage.warning(`仅支持【 png】文件!`);
        }

        return false;
      }
      if (!isSize) {
        ElMessage.warning(`文件大小应小于10MB!`);
        return false;
      }

      return isSize;
    };

    //移除文件列表文件
    const handelRemove = (file: any) => {
      state.attachList = state.attachList.filter((x: any) => x.url != file.url);
      emit("update:modelValue", state.attachList);
    };

    const handleDownLoad = async (file) => {
      let res = await downloadZiliao({
        filePath: file.url,
      });
      downloadFile(res, file.name);
    };

    watchEffect(() => {
      if (props.modelValue) {
        state.attachList = props.modelValue;
      }
    });

    onBeforeMount(() => {});

    return {
      ...toRefs(state),
      beforeUpload,
      toUpload,
      handelRemove,
      getfilePath,
      handleDownLoad,
      fileSuccess,
    };
  },
});
</script>
